<script setup>
  import { defineProps, ref } from "vue";
  import { ElMessage } from "element-plus";
  import commonApi from "@/api/common/index.js";
  import ResponseUtil from "@/utils/ResponseUtil.js";

  const props = defineProps({
    target: String,
    workType: Number
  })

  let loading = ref(false);
  let waiting = ref(false);
  let text = ref("获取验证码");
  let waitingTime = ref(60);
  let timer = null;

  // 获取验证码
  const getVerifyCode = () => {
    // 不允许重复发送
    if (loading.value || waiting.value) return;

    // 校验参数
    if (props.target === '' || props.target === null) {
      ElMessage.error('请输入账号');
      return;
    }

    // 获取按钮开始加载
    loading.value = true;

    // 向服务器发送请求
    commonApi.getVerifyCode(props.target, props.workType).then(response => {
      // 获取按钮结束加载
      loading.value = false;

      // 处理结果
      ResponseUtil.data(response).dispose(response => {
        // 判断是否获取成功
        if (response.code === '200') {
          // 发送成功提醒
          ElMessage.success('验证码发送成功');

          // 按钮显示文字更新
          text.value = waitingTime.value + '秒后重新获取';

          // 获取按钮进入等待状态
          waiting.value = true;

          // 开启计时器进行倒计时
          timer = setInterval(() => {
            // 等待时间递减
            waitingTime.value--;

            // 判断是否为最后一秒，终止计时器
            if (waitingTime.value === 0) {
              // 取消按钮等待状态
              waiting.value = false;

              // 按钮显示文字更新
              text.value = '重新获取';

              // 终止计时器
              clearInterval(timer);

              // 重置时间
              waitingTime.value = 60;

              return;
            }

            // 按钮显示文字更新
            text.value = waitingTime.value + '秒后重新获取';
          }, 1000);

          return;
        }
        // 请求失败
        ElMessage.error(response.message);
      })

    })
  }
</script>

<template>
  <div v-loading="loading" element-loading-background="rgb(242, 242, 242)"
       :style="!waiting ? '':'color:white; background-color: rgb(51, 127, 218);'"
       :class="['send-code-button']"
       @click="getVerifyCode()">{{ text }}</div>
</template>

<style scoped>
  /* 发送验证码按钮样式 */
  .send-code-button {
    width: 35%;
    height: 42px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    font-size: 14px;
    color: rgb(0, 102, 204);
    background-color: rgb(242, 242, 242);
    transition: all .2s;
  }

  /* 发送验证码按钮悬浮样式 */
  .send-code-button:hover {
    cursor: pointer;
    background-color: rgb(51, 127, 218);
    color: white;
  }

  .verify-waiting-style {
    background-color: rgb(51, 127, 218);
    color:white;
  }
  .verify-not-waiting-style {
    color: rgb(0, 102, 204);
    background-color: rgb(242, 242, 242);
  }
</style>